<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="baidu-site-verification" content="L6Lm9d5Crl"/>
  
  
  
  
  <title>关于Handlebars.js模板引擎，你想知道的都在这里 | 魏阁的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Handlebars.js模板引擎是我们常用到的模板引擎，它是 JavaScript 一个语义模板库，通过对view和data的分离来快速构建web模板。它采用”Logic-less template”（无逻辑模版）的思路，在加载时被预编译，而不是到了客户端执行到代码时再去编译，这样可以保证模板加载和运行的速度。Handlebars兼容Mustache，你可以在Handlebars中导入Must">
<meta name="keywords" content="Handlebars">
<meta property="og:type" content="article">
<meta property="og:title" content="关于Handlebars.js模板引擎，你想知道的都在这里">
<meta property="og:url" content="http://yoursite.com/2017/12/25/handlebars/index.html">
<meta property="og:site_name" content="魏阁的博客">
<meta property="og:description" content="Handlebars.js模板引擎是我们常用到的模板引擎，它是 JavaScript 一个语义模板库，通过对view和data的分离来快速构建web模板。它采用”Logic-less template”（无逻辑模版）的思路，在加载时被预编译，而不是到了客户端执行到代码时再去编译，这样可以保证模板加载和运行的速度。Handlebars兼容Mustache，你可以在Handlebars中导入Must">
<meta property="og:updated_time" content="2017-12-25T10:22:16.277Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="关于Handlebars.js模板引擎，你想知道的都在这里">
<meta name="twitter:description" content="Handlebars.js模板引擎是我们常用到的模板引擎，它是 JavaScript 一个语义模板库，通过对view和data的分离来快速构建web模板。它采用”Logic-less template”（无逻辑模版）的思路，在加载时被预编译，而不是到了客户端执行到代码时再去编译，这样可以保证模板加载和运行的速度。Handlebars兼容Mustache，你可以在Handlebars中导入Must">
  
    <link rel="alternative" href="/atom.xml" title="魏阁的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/img/favicon.png">
  
  
  <link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
  
  
      <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  
  <!-- 加载特效 -->
    <script src="/js/pace.js"></script>
    <link href="/css/pace/pace-theme-flash.css" rel="stylesheet" />
  <script>
      var yiliaConfig = {
          fancybox: true,
          animate: true,
          isHome: false,
          isPost: true,
          isArchive: false,
          isTag: false,
          isCategory: false,
          open_in_new: false
      }
  </script>
</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <script src="//7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
        <a href="/" class="profilepic">
            
            <img lazy-src="/img/mine.png" class="js-avatar">
            
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">魏阁</a></h1>
        </hgroup>
        
        
            <form>
                <input type="text" class="st-default-search-input search" id="local-search-input" placeholder="搜索一下" autocomplete="off">
            </form>
            <div id="local-search-result"></div>
        
        
            <script type="text/javascript">
                (function() {
                    'use strict';
                    function getMatchData(keyword, data) {
                        var matchData = [];
                        for(var i =0;i<data.length;i++){
                            if(data[i].title.toLowerCase().indexOf(keyword)>=0) 
                                matchData.push(data[i])
                        }
                        return matchData;
                    }
                    var $input = $('#local-search-input');
                    var $resultContent = $('#local-search-result');
                    $input.keyup(function(){
                        $.ajax({
                            url: '/search.json',
                            dataType: "json",
                            success: function( json ) {
                                var str='<ul class=\"search-result-list\">';                
                                var keyword = $input.val().trim().toLowerCase();
                                $resultContent.innerHTML = "";
                                if ($input.val().trim().length <= 0) {
                                    $resultContent.empty();
                                    $('#switch-area').show();
                                    return;
                                }
                                var results = getMatchData(keyword, json);
                                if(results.length === 0){
                                    $resultContent.empty();
                                    $('#switch-area').show();
                                    return;
                                } 
                                for(var i =0; i<results.length; i++){
                                    str += "<li><a href='"+ results[i].url +"' class='search-result-title'>"+ results[i].title +"</a></li>";
                                }
                                str += "</ul>";
                                $resultContent.empty();
                                $resultContent.append(str);
                                $('#switch-area').hide();
                            }
                        });
                    });
                })();
            </script>
        
        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        
        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a  href="/archives/">所有文章</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fl github"  target="_blank" href="https://github.com/gezi666" title="github">github</a>
                            
                                <a class="fl rss"  target="_blank" href="/atom.xml" title="rss">rss</a>
                            
                        </ul>
                    </nav>
                </section>
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <a href="/tags/DOM/" style="font-size: 10px;">DOM</a> <a href="/tags/Handlebars/" style="font-size: 10px;">Handlebars</a> <a href="/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/tags/print/" style="font-size: 10px;">print</a> <a href="/tags/vue/" style="font-size: 10px;">vue</a>
                    </div>
                </section>
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a target="_blank"  class="main-nav-link switch-friends-link" href="http://blog.csdn.net/baidu_21483933">csdn</a>
                    
                      <a target="_blank"  class="main-nav-link switch-friends-link" href="https://segmentfault.com/blog/maocg_web">segmentfault</a>
                    
                      <a target="_blank"  class="main-nav-link switch-friends-link" href="http://www.jianshu.com/users/eb37ef89c746/latest_articles">简书</a>
                    
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">爱旅行,爱购物,爱运动,爱编程,爱的太多了!</div>
                </section>
                
            </div>
        </div>
    </header>
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">魏阁</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                
                    <img lazy-src="/img/mine.png" class="js-avatar">
                
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">魏阁</a></h1>
            </hgroup>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/archives/">所有文章</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                <div class="social">
                    
                        <a class="github" target="_blank" href="https://github.com/gezi666" title="github">github</a>
                    
                        <a class="rss" target="_blank" href="/atom.xml" title="rss">rss</a>
                    
                </div>
            </nav>
        </header>                
    </div>
</nav>
      <div class="body-wrap"><article id="post-handlebars" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/2017/12/25/handlebars/" class="article-date">
      <time datetime="2017-12-24T16:00:00.000Z" itemprop="datePublished">2017-12-25</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      关于Handlebars.js模板引擎，你想知道的都在这里
    </h1>
  


      </header>
      
      <div class="article-info article-info-post">
        

        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Handlebars/">Handlebars</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <hr>
<p>Handlebars.js模板引擎是我们常用到的模板引擎，它是 JavaScript 一个语义模板库，通过对view和data的分离来快速构建web模板。它采用”Logic-less template”（无逻辑模版）的思路，在加载时被预编译，而不是到了客户端执行到代码时再去编译，这样可以保证模板加载和运行的速度。Handlebars兼容Mustache，你可以在Handlebars中导入Mustache模板。<br>本文对它的一些实用方法做了一些简单的总结，希望你在这里可以找到想用的方法。</p>
<a id="more"></a>
<h1 id="使用与安装"><a href="#使用与安装" class="headerlink" title="使用与安装"></a>使用与安装</h1><p>Handlebars的安装非常简单，你只需要从Github下载最新版本，你也可访问下面网址获取最新信息：<a href="http://handlebarsjs.com。" target="_blank" rel="external">http://handlebarsjs.com。</a></p>
<p>目前handlebars.js已经被许多项目广泛使用了，handlebars是一个纯JS库，因此你可以像使用其他JS脚本一样用script标签来包含handlebars.js<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;script type="text/javascript" src=".js/handlebars.js"&gt;&lt;/script&gt;</div></pre></td></tr></table></figure></p>
<h1 id="基本语法"><a href="#基本语法" class="headerlink" title="基本语法"></a>基本语法</h1><p>先来段实例看看</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">//html片段</div><div class="line">&lt;div id='demo'&gt;&lt;/div&gt;</div><div class="line">&lt;script id="demo-template" type="text/x-handlebars-template"&gt;</div><div class="line">    &lt;p&gt;&#123;&#123;title&#125;&#125;&lt;/p&gt;</div><div class="line">&lt;/script&gt;</div><div class="line"></div><div class="line">//js片段 （这里以jquery的写法为例）</div><div class="line">//预编译模板</div><div class="line">var template = Handlebars.compile($("#demo-template").html());</div><div class="line">//输入模板（data为需要渲染的数据，如：&#123;"text":"Hello World!"&#125;）</div><div class="line">$("#demo").html(template(data));</div></pre></td></tr></table></figure>
<h2 id="handlebars-表达式"><a href="#handlebars-表达式" class="headerlink" title="handlebars 表达式"></a>handlebars 表达式</h2><p>Handlebars expressions是handlebars模板中最基本的单元，使用方法是加两个大括号&#123;&#123; expression &#125;&#125;, handlebars模板会自动匹配相应的数值，对象甚至是函数。<br>上例中&#123;&#123; title &#125;&#125;表示在上下文中找<code>title</code>属性，获取它的值。</p>
<h2 id="点分割表达式"><a href="#点分割表达式" class="headerlink" title="点分割表达式"></a>点分割表达式</h2><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;h1&gt;&#123;&#123;article.title&#125;&#125;&lt;/h1&gt;</div></pre></td></tr></table></figure>
<p>当前上下文找<code>article</code>属性，再找它的<code>title</code>属性</p>
<h2 id="不转义表达式"><a href="#不转义表达式" class="headerlink" title="不转义表达式"></a>不转义表达式</h2><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;&#123;&lt;p&gt;Hello World!&lt;/P&gt;&#125;&#125;&#125;</div></pre></td></tr></table></figure>
<p>当有些内容不想被转义时，需要使用3个大括号包&#123;&#123;&#123;起来。</p>
<h1 id="Handlebar的表达式"><a href="#Handlebar的表达式" class="headerlink" title="Handlebar的表达式"></a>Handlebar的表达式</h1><h2 id="Block表达式"><a href="#Block表达式" class="headerlink" title="Block表达式"></a>Block表达式</h2><p>有时候当你需要对某条表达式进行更深入的操作时，Blocks就派上用场了，在Handlebars中，你可以在表达式后面跟随一个#号来表示Blocks，然后通过&#123;&#123; 表达式 &#125;&#125;来结束Blocks。 如果当前的表达式是一个数组，则Handlebars会“自动展开数组”，并将Blocks的上下文设为数组中的元素。 例如：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;ul&gt;</div><div class="line">&#123;&#123;#programme&#125;&#125;</div><div class="line">    &lt;li&gt;&#123;&#123;language&#125;&#125;&lt;/li&gt;</div><div class="line">&#123;&#123;/programme&#125;&#125;</div><div class="line">&lt;/ul&gt;</div></pre></td></tr></table></figure>
<p>有以下json数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  programme: [</div><div class="line">    &#123;language: <span class="string">"JavaScript"</span>&#125;,</div><div class="line">    &#123;language: <span class="string">"HTML"</span>&#125;,</div><div class="line">    &#123;language: <span class="string">"CSS"</span>&#125;</div><div class="line">  ]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>编译模板代码会自动匹配<code>programme</code>数据并展开数据，渲染DOM后就是这样的</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;ul&gt;</div><div class="line">  &lt;li&gt;JavaScript&lt;/li&gt;</div><div class="line">  &lt;li&gt;HTML&lt;/li&gt;</div><div class="line">  &lt;li&gt;CSS&lt;/li&gt;</div><div class="line">&lt;/ul&gt;</div></pre></td></tr></table></figure>
<h1 id="Handlebars的内置块表达式（Block-helper）"><a href="#Handlebars的内置块表达式（Block-helper）" class="headerlink" title="Handlebars的内置块表达式（Block helper）"></a>Handlebars的内置块表达式（Block helper）</h1><h2 id="1-each-block-helper"><a href="#1-each-block-helper" class="headerlink" title="1.each block helper"></a>1.each block helper</h2><p>你可以使用内置的&#123;&#123; each &#125;&#125; helper遍历列表块内容，用<code>this</code>来引用遍历的元素 例如：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;ul&gt;</div><div class="line">    &#123;&#123;#each name&#125;&#125;</div><div class="line">        &lt;li&gt;&#123;&#123;this&#125;&#125;&lt;/li&gt;</div><div class="line">    &#123;&#123;/each&#125;&#125;</div><div class="line">&lt;/ul&gt;</div></pre></td></tr></table></figure>
<p>对应适用的json数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    name: [<span class="string">"html"</span>,<span class="string">"css"</span>,<span class="string">"javascript"</span>]</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里的<code>this</code>指的是数组里的每一项元素，和上面的Block很像，但原理是不一样的这里的<code>name</code>是数组，而内置的<code>each</code>就是为了遍历数组用的，更复杂的数据也同样适用。</p>
<p>通过<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;@index&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>可以引用当前的循环索引<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;<span class="comment">#each array&#125;&#125;</span></div><div class="line">  &#123;&#123;@index&#125;&#125;: &#123;&#123;this&#125;&#125;</div><div class="line">&#123;&#123;/each&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>用<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;@key&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>可以引用当前的键名<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;<span class="comment">#each object&#125;&#125;</span></div><div class="line">  &#123;&#123;@key&#125;&#125;: &#123;&#123;this&#125;&#125;</div><div class="line">&#123;&#123;/each&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>数组迭代的第一步和最后一步用 <code>@first</code> 和 <code>@last</code> 变量表示， 对象迭代时仅 <code>@first</code> 可用。</p>
<h2 id="2-with-block-helper"><a href="#2-with-block-helper" class="headerlink" title="2.with block helper"></a>2.with block helper</h2><p>&#123;&#123; #with &#125;&#125;命令可以让当前的上下文进入到一个属性中,这个方法在操作复杂的template时候非常有用。<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&lt;div class="entry"&gt;</div><div class="line">  &lt;h1&gt;&#123;&#123;title&#125;&#125;&lt;/h1&gt;</div><div class="line">  &#123;&#123;#with author&#125;&#125;</div><div class="line">  &lt;h2&gt;By &#123;&#123;firstName&#125;&#125; &#123;&#123;lastName&#125;&#125;&lt;/h2&gt;</div><div class="line">  &#123;&#123;/with&#125;&#125;</div><div class="line">&lt;/div&gt;</div></pre></td></tr></table></figure></p>
<p>对应适用json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  title: <span class="string">"My first post!"</span>,</div><div class="line">  author: &#123;</div><div class="line">    firstName: <span class="string">"Charles"</span>,</div><div class="line">    lastName: <span class="string">"Jolley"</span></div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>渲染DOM后<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&lt;div class="entry"&gt;</div><div class="line">  &lt;h1&gt;My first post!&lt;/h1&gt;</div><div class="line">  &lt;h2&gt;By Charles Jolley&lt;/h2&gt;</div><div class="line">&lt;/div&gt;</div></pre></td></tr></table></figure></p>
<h3 id="with-进入到某个属性-进入到某个上下文环境-："><a href="#with-进入到某个属性-进入到某个上下文环境-：" class="headerlink" title="with-进入到某个属性(进入到某个上下文环境)："></a>with-进入到某个属性(进入到某个上下文环境)：</h3><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">html片段</div><div class="line">&lt;table&gt;</div><div class="line">   &lt;thead&gt;</div><div class="line">     &lt;tr&gt;</div><div class="line">       &lt;th&gt;姓名&lt;/th&gt;</div><div class="line">       &lt;th&gt;性别&lt;/th&gt;</div><div class="line">       &lt;th&gt;年龄&lt;/th&gt;</div><div class="line">       &lt;th&gt;兴趣爱好&lt;/th&gt;</div><div class="line">     &lt;/tr&gt;</div><div class="line">   &lt;/thead&gt;</div><div class="line">   &lt;tbody id="tableList"&gt;</div><div class="line"></div><div class="line">   &lt;/tbody&gt;</div><div class="line">   &lt;script id="table-template" type="text/x-handlebars-template"&gt;</div><div class="line">       &#123;&#123;#each this&#125;&#125;</div><div class="line">         &lt;tr&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;name&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;sex&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;age&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;</div><div class="line">             &#123;&#123;#with favorite&#125;&#125;</div><div class="line">               &#123;&#123;#each this&#125;&#125;</div><div class="line">                 &lt;p&gt;&#123;&#123;name&#125;&#125;&lt;/p&gt;</div><div class="line">               &#123;&#123;/each&#125;&#125;</div><div class="line">             &#123;&#123;/with&#125;&#125;</div><div class="line">           &lt;/td&gt;</div><div class="line">         &lt;/tr&gt;</div><div class="line">       &#123;&#123;/each&#125;&#125;</div><div class="line">   &lt;/script&gt;</div><div class="line"> &lt;/table&gt;</div></pre></td></tr></table></figure>
<p>对应适用json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">      <span class="string">"name"</span>: <span class="string">"张三"</span>,</div><div class="line">      <span class="string">"sex"</span>: <span class="string">"0"</span>,</div><div class="line">      <span class="string">"age"</span>: <span class="number">18</span>,</div><div class="line">      <span class="string">"favorite"</span>:</div><div class="line">      [</div><div class="line">      &#123;</div><div class="line">         <span class="string">"name"</span>:<span class="string">"唱歌"</span></div><div class="line">       &#125;,&#123;</div><div class="line">         <span class="string">"name"</span>:<span class="string">"篮球"</span></div><div class="line">       &#125;</div><div class="line">     ]</div><div class="line"> &#125;,</div><div class="line">&#123;</div><div class="line">     <span class="string">"name"</span>: <span class="string">"李四"</span>,</div><div class="line">     <span class="string">"sex"</span>: <span class="string">"0"</span>,</div><div class="line">     <span class="string">"age"</span>: <span class="number">22</span>,</div><div class="line">     <span class="string">"favorite"</span>:</div><div class="line">     [</div><div class="line">       &#123;</div><div class="line">         <span class="string">"name"</span>:<span class="string">"上网"</span></div><div class="line">      &#125;,&#123;</div><div class="line">         <span class="string">"name"</span>:<span class="string">"足球"</span></div><div class="line">      &#125;</div><div class="line">     ]</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="with-终极this应用："><a href="#with-终极this应用：" class="headerlink" title="with-终极this应用："></a>with-终极this应用：</h3><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">html片段</div><div class="line">&lt;table&gt;</div><div class="line">   &lt;thead&gt;</div><div class="line">     &lt;tr&gt;</div><div class="line">       &lt;th&gt;姓名&lt;/th&gt;</div><div class="line">       &lt;th&gt;性别&lt;/th&gt;</div><div class="line">       &lt;th&gt;年龄&lt;/th&gt;</div><div class="line">       &lt;th&gt;兴趣爱好&lt;/th&gt;</div><div class="line">     &lt;/tr&gt;</div><div class="line">   &lt;/thead&gt;</div><div class="line">   &lt;tbody id="tableList"&gt;</div><div class="line"></div><div class="line">   &lt;/tbody&gt;</div><div class="line">   &lt;script id="table-template" type="text/x-handlebars-template"&gt;</div><div class="line">       &#123;&#123;#each this&#125;&#125;</div><div class="line">         &lt;tr&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;name&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;sex&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;age&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;</div><div class="line">             &#123;&#123;#with favorite&#125;&#125;</div><div class="line">               &#123;&#123;#each this&#125;&#125;</div><div class="line">                 &lt;p&gt;&#123;&#123;this&#125;&#125;&lt;/p&gt;</div><div class="line">               &#123;&#123;/each&#125;&#125;</div><div class="line">             &#123;&#123;/with&#125;&#125;</div><div class="line">           &lt;/td&gt;</div><div class="line">         &lt;/tr&gt;</div><div class="line">       &#123;&#123;/each&#125;&#125;</div><div class="line">   &lt;/script&gt;</div><div class="line"> &lt;/table&gt;</div></pre></td></tr></table></figure>
<p>对应适用json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">      <span class="string">"name"</span>: <span class="string">"张三"</span>,</div><div class="line">      <span class="string">"sex"</span>: <span class="string">"0"</span>,</div><div class="line">      <span class="string">"age"</span>: <span class="number">18</span>,</div><div class="line">      <span class="string">"favorite"</span>:</div><div class="line">      [</div><div class="line">          <span class="string">"唱歌"</span>,</div><div class="line">          <span class="string">"篮球"</span></div><div class="line">      ]</div><div class="line"> &#125;,</div><div class="line">&#123;</div><div class="line">     <span class="string">"name"</span>: <span class="string">"李四"</span>,</div><div class="line">     <span class="string">"sex"</span>: <span class="string">"0"</span>,</div><div class="line">     <span class="string">"age"</span>: <span class="number">22</span>,</div><div class="line">     <span class="string">"favorite"</span>:</div><div class="line">     [</div><div class="line">          <span class="string">"上网"</span>,</div><div class="line">          <span class="string">"足球"</span></div><div class="line">     ]</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="3-if-else-block-helper"><a href="#3-if-else-block-helper" class="headerlink" title="3.if else block helper"></a>3.if else block helper</h2><p>&#123;&#123; #if &#125;&#125;就你使用JavaScript一样，你可以指定条件渲染DOM，如果它的参数返回false，undefined, null, “” 或者 [] (a “falsy” value), Handlebar将不会渲染DOM，如果存在&#123;&#123; else &#125;&#125;则执行&#123;&#123; else &#125;&#125;后面的渲染<br>例如：<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;#if list&#125;&#125;</div><div class="line">&lt;ul id="list"&gt;</div><div class="line">    &#123;&#123;#each list&#125;&#125;</div><div class="line">        &lt;li&gt;&#123;&#123;this&#125;&#125;&lt;/li&gt;</div><div class="line">    &#123;&#123;/each&#125;&#125;</div><div class="line">&lt;/ul&gt;</div><div class="line">&#123;&#123;else&#125;&#125;</div><div class="line">    &lt;p&gt;&#123;&#123;error&#125;&#125;&lt;/p&gt;</div><div class="line">&#123;&#123;/if&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>对应适用json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">var data = &#123;</div><div class="line">    info:[<span class="string">'HTML5'</span>,<span class="string">'CSS3'</span>,<span class="string">"WebGL"</span>],</div><div class="line">    <span class="string">"error"</span>:<span class="string">"数据取出错误"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这里&#123;&#123; #if &#125;&#125;判断是否存在<code>list</code>数组，如果存在则遍历<code>list</code>，如果不存在输出错误信息。</p>
<h2 id="4-unless-block-helper"><a href="#4-unless-block-helper" class="headerlink" title="4.unless block helper"></a>4.unless block helper</h2><p>&#123;&#123; unless &#125;&#125;这个语法是反向的<code>if</code>语法也就是当判断的值为<code>false</code>时他会渲染DOM 例如：<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;#unless data&#125;&#125;</div><div class="line">&lt;ul id="list"&gt;</div><div class="line">    &#123;&#123;#each list&#125;&#125;</div><div class="line">        &lt;li&gt;&#123;&#123;this&#125;&#125;&lt;/li&gt;</div><div class="line">    &#123;&#123;/each&#125;&#125;</div><div class="line">&lt;/ul&gt;</div><div class="line">&#123;&#123;else&#125;&#125;</div><div class="line">    &lt;p&gt;&#123;&#123;error&#125;&#125;&lt;/p&gt;</div><div class="line">&#123;&#123;/unless&#125;&#125;</div></pre></td></tr></table></figure></p>
<h1 id="Handlebars的访问（Path）"><a href="#Handlebars的访问（Path）" class="headerlink" title="Handlebars的访问（Path）"></a>Handlebars的访问（Path）</h1><p>Handlebar支持路径和mustache,Handlebar还支持嵌套的路径，使得能够查找嵌套低于当前上下文的属性可以通过<code>.</code>来访问属性,也可以使用<code>../</code>,来访问父级属性。 例如:（使用<code>.</code>访问的例子）<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&lt;h1&gt;&#123;&#123;author.id&#125;&#125;&lt;/h1&gt;</div></pre></td></tr></table></figure></p>
<p>对应json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">  title: <span class="string">"My First Blog Post!"</span>,</div><div class="line">  author: &#123;</div><div class="line">    id: <span class="number">47</span>,</div><div class="line">    name: <span class="string">"Yehuda Katz"</span></div><div class="line">  &#125;,</div><div class="line">  body: <span class="string">"My first post. Wheeeee!"</span></div><div class="line">  &#125;</div></pre></td></tr></table></figure></p>
<p>例如：（使用<code>../</code>访问）<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">&#123;&#123;#with person&#125;&#125;</div><div class="line">    &lt;h1&gt;&#123;&#123;../company.name&#125;&#125;&lt;/h1&gt;</div><div class="line">&#123;&#123;/with&#125;&#125;</div></pre></td></tr></table></figure></p>
<p>对应适用json数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&#123;</div><div class="line">    <span class="string">"person"</span>:</div><div class="line">    &#123; <span class="string">"name"</span>: <span class="string">"Alan"</span> &#125;,</div><div class="line">        company:</div><div class="line">    &#123;<span class="string">"name"</span>: <span class="string">"Rad, Inc."</span> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h1 id="自定义helper"><a href="#自定义helper" class="headerlink" title="自定义helper"></a>自定义helper</h1><p>很多时候，我们需要更加复杂的<code>if</code>判断逻辑，显然默认的<code>if</code>不能满足我们的需求。这时你可以使用Handlebars.registerHelper()方法来注册一个<code>helper</code>。<br>先看一个例子：<br><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div></pre></td><td class="code"><pre><div class="line">html片段</div><div class="line"> &lt;script id="table-template" type="text/x-handlebars-template"&gt;</div><div class="line">   &#123;&#123;#each student&#125;&#125;</div><div class="line">     &#123;&#123;#if name&#125;&#125;</div><div class="line">       &#123;&#123;#compare age 20&#125;&#125;</div><div class="line">         &lt;tr&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;name&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;transformat sex&#125;&#125;&lt;/td&gt;</div><div class="line">           &lt;td&gt;&#123;&#123;age&#125;&#125;&lt;/td&gt;</div><div class="line">         &lt;/tr&gt;</div><div class="line">       &#123;&#123;else&#125;&#125;</div><div class="line">         &lt;tr&gt;</div><div class="line">           &lt;td&gt;?&lt;/td&gt;</div><div class="line">           &lt;td&gt;?&lt;/td&gt;</div><div class="line">           &lt;td&gt;?&lt;/td&gt;</div><div class="line">         &lt;/tr&gt;</div><div class="line">       &#123;&#123;/compare&#125;&#125;</div><div class="line">     &#123;&#123;/if&#125;&#125;</div><div class="line">   &#123;&#123;/each&#125;&#125;</div><div class="line">&lt;/script&gt;</div><div class="line"></div><div class="line">js片段：</div><div class="line">//注册一个比较大小的Helper,判断v1是否大于v2</div><div class="line"> Handlebars.registerHelper("compare",function(v1,v2,options)&#123;</div><div class="line">   if(v1&gt;v2)&#123;</div><div class="line">     //满足添加继续执行</div><div class="line">     return options.fn(this);</div><div class="line">   &#125;else&#123;</div><div class="line">     //不满足条件执行&#123;&#123;else&#125;&#125;部分</div><div class="line">     return options.inverse(this);</div><div class="line">   &#125;</div><div class="line"> &#125;);</div><div class="line"></div><div class="line"> //注册一个翻译用的Helper，0翻译成男，1翻译成女</div><div class="line"> Handlebars.registerHelper("transformat",function(value)&#123;</div><div class="line">   if(value==0)&#123;</div><div class="line">     return "男";</div><div class="line">   &#125;else if(value==1)&#123;</div><div class="line">     return "女";</div><div class="line">   &#125;</div><div class="line"> &#125;);</div><div class="line"></div><div class="line">json数据:</div><div class="line">&#123;</div><div class="line">     "student": [</div><div class="line">         &#123;</div><div class="line">             "name": "张三",</div><div class="line">             "sex": "0",</div><div class="line">             "age": 23</div><div class="line">         &#125;,</div><div class="line">         &#123;</div><div class="line">             "sex": "0",</div><div class="line">             "age": 22</div><div class="line">         &#125;,</div><div class="line">         &#123;</div><div class="line">             "name": "妞妞",</div><div class="line">             "sex": "1",</div><div class="line">             "age": 18</div><div class="line">         &#125;</div><div class="line">     ]</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>本例中，利用Handlebars.js中Helper强大的扩展性，定义了一个<code>compare</code>，它用来比较两个数的大小，如果第一个数大于第二个数，满足条件继续执行，否则执行&#123;&#123; else &#125;&#125;部分。</p>
<p>Handlebars.registerHelper用来定义Helper，它有两个参数，第一个参数是Helper名称，第二个参数是一个回调函数，用来执行核心业务逻辑。本例中的函数，有三个参数，其中前两个参数是需要比较的两个数，第三个参数是固定的，就叫<code>options</code>，如果加了该参数，就说明这个Helper是一个Block，块级别的Helper，有一定的语法结构，调用的时候加#号，就像<code>if</code>那样。</p>
<p>关于<code>options</code>的使用，我所了解的就是这种用法，<code>return options.fn(this);</code>表示满足条件继续执行，也就是执行&#123;&#123;&#35; compare &#125;&#125;和&#123;&#123; else &#125;&#125;之间的代码；<code>return options.inverse(this);</code>表示不满足条件，也就是执行&#123;&#123; else &#125;&#125;和&#123;&#123; /compare &#125;&#125;之间的代码。</p>
<p>由于这是一个块级别的Helper，所以调用要加#，例如：&#123;&#123; #compare age 20 &#125;&#125;，其中的age就是当前上下文中读取到的年龄，20是我随便写的值，意思是只要age比20大，就显示，否则全显示?。</p>
<p>可以看出，Helper中写的可以是任何js代码，现在想想，就知道Handlebars有多灵活了吧！！</p>
<p>上面注册的两个Helper，一个带options参数，另一个不带；带options参数的Helper是块级别的，而不带的，相当于行内级别的Helper。</p>
<p>从例子一开始，性别就是用0、1代码表示的，但实际情况下我们需要转换成汉字，<code>transformat</code>这个Helper需要一个参数，根据不同的代码，返回男女，这样调用&#123;&#123; transformat sex &#125;&#125;，其中sex是从当前上下文中读取的性别代码。</p>
<h1 id="内建工具"><a href="#内建工具" class="headerlink" title="内建工具"></a>内建工具</h1><h2 id="转义字符串"><a href="#转义字符串" class="headerlink" title="转义字符串"></a>转义字符串</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.escapeExpression(string)</div></pre></td></tr></table></figure>
<h2 id="判断空值"><a href="#判断空值" class="headerlink" title="判断空值"></a>判断空值</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.isEmpty(value)</div></pre></td></tr></table></figure>
<h2 id="扩展对象"><a href="#扩展对象" class="headerlink" title="扩展对象"></a>扩展对象</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.extend(foo, &#123;bar: true&#125;)</div></pre></td></tr></table></figure>
<h2 id="转字符串"><a href="#转字符串" class="headerlink" title="转字符串"></a>转字符串</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.toString(obj)</div></pre></td></tr></table></figure>
<h2 id="判断数组"><a href="#判断数组" class="headerlink" title="判断数组"></a>判断数组</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.isArray(obj)</div></pre></td></tr></table></figure>
<h2 id="判断函数"><a href="#判断函数" class="headerlink" title="判断函数"></a>判断函数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Handlebars.Utils.isFunction(obj)</div></pre></td></tr></table></figure>

      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a  href="/2017/12/25/handlebars/">关于Handlebars.js模板引擎，你想知道的都在这里</a></p>
        <p><span>文章作者:</span><a  href="/" title="访问 魏阁 的个人博客">魏阁</a></p>
        <p><span>发布时间:</span>2017年12月25日 - 00时00分</p>
        <p><span>最后更新:</span>2017年12月25日 - 18时22分</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="/2017/12/25/handlebars/" title="关于Handlebars.js模板引擎，你想知道的都在这里">http://yoursite.com/2017/12/25/handlebars/</a>
            <span class="copy-path" data-clipboard-text="原文: http://yoursite.com/2017/12/25/handlebars/　　作者: 魏阁" title=""></span>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/cn/" title="中国大陆 (CC BY-NC-SA 3.0 CN)" target = "_blank">"署名-非商用-相同方式共享 3.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



<nav id="article-nav">
  
  
    <a  href="/2017/09/27/browser-rendering/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">深入浏览器渲染原理(一) — 浏览器渲染DOM过程</div>
      <strong class="article-nav-caption">></strong>
    </a>
  
</nav>


  
</article>

    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#使用与安装"><span class="toc-number">1.</span> <span class="toc-text">使用与安装</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#基本语法"><span class="toc-number">2.</span> <span class="toc-text">基本语法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#handlebars-表达式"><span class="toc-number">2.1.</span> <span class="toc-text">handlebars 表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#点分割表达式"><span class="toc-number">2.2.</span> <span class="toc-text">点分割表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#不转义表达式"><span class="toc-number">2.3.</span> <span class="toc-text">不转义表达式</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Handlebar的表达式"><span class="toc-number">3.</span> <span class="toc-text">Handlebar的表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Block表达式"><span class="toc-number">3.1.</span> <span class="toc-text">Block表达式</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Handlebars的内置块表达式（Block-helper）"><span class="toc-number">4.</span> <span class="toc-text">Handlebars的内置块表达式（Block helper）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-each-block-helper"><span class="toc-number">4.1.</span> <span class="toc-text">1.each block helper</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-with-block-helper"><span class="toc-number">4.2.</span> <span class="toc-text">2.with block helper</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#with-进入到某个属性-进入到某个上下文环境-："><span class="toc-number">4.2.1.</span> <span class="toc-text">with-进入到某个属性(进入到某个上下文环境)：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#with-终极this应用："><span class="toc-number">4.2.2.</span> <span class="toc-text">with-终极this应用：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-if-else-block-helper"><span class="toc-number">4.3.</span> <span class="toc-text">3.if else block helper</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-unless-block-helper"><span class="toc-number">4.4.</span> <span class="toc-text">4.unless block helper</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Handlebars的访问（Path）"><span class="toc-number">5.</span> <span class="toc-text">Handlebars的访问（Path）</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#自定义helper"><span class="toc-number">6.</span> <span class="toc-text">自定义helper</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#内建工具"><span class="toc-number">7.</span> <span class="toc-text">内建工具</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#转义字符串"><span class="toc-number">7.1.</span> <span class="toc-text">转义字符串</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#判断空值"><span class="toc-number">7.2.</span> <span class="toc-text">判断空值</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#扩展对象"><span class="toc-number">7.3.</span> <span class="toc-text">扩展对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#转字符串"><span class="toc-number">7.4.</span> <span class="toc-text">转字符串</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#判断数组"><span class="toc-number">7.5.</span> <span class="toc-text">判断数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#判断函数"><span class="toc-number">7.6.</span> <span class="toc-text">判断函数</span></a></li></ol></li></ol>
</div>
<style>
    .left-col .switch-btn {
        display: none;
    }
    .left-col .switch-area {
        display: none;
    }
</style>
<input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">
<script src="https://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script>
    var valueHide = "隐藏目录";
    var valueShow = "显示目录";
    if ($(".left-col").is(":hidden")) {
        $("#tocButton").attr("value", valueShow);
    }
    $("#tocButton").click(function() {
        if ($("#toc").is(":hidden")) {
            $("#tocButton").attr("value", valueHide);
            $("#toc").slideDown(320);
            $(".switch-btn, .switch-area").fadeOut(300);
        }
        else {
            $("#tocButton").attr("value", valueShow);
            $("#toc").slideUp(350);
            $(".switch-btn, .switch-area").fadeIn(500);
        }
    })
    if ($(".toc").length < 1) {
        $("#toc, #tocButton").hide();
        $(".switch-btn, .switch-area").show();
    }
</script>




<!--<div class="bdsharebuttonbox">-->
	<!--<a href="#" class="fx fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>-->
	<!--<a href="#" class="fx fa-weixin bds_weixin" data-cmd="weixin" title="分享到微信"></a>-->
	<!--<a href="#" class="fx fa-qq bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>-->
	<!--<a href="#" class="fx fa-facebook-official bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>-->
	<!--<a href="#" class="fx fa-twitter bds_twi" data-cmd="twi" title="分享到Twitter"></a>-->
	<!--<a href="#" class="fx fa-linkedin bds_linkedin" data-cmd="linkedin" title="分享到linkedin"></a>-->
	<!--<a href="#" class="fx fa-files-o bds_copy" data-cmd="copy" title="分享到复制网址"></a>-->
<!--</div>-->
<!--<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"2","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>-->




    
        <section class="changyan" id="comments">
  <!--<div id="uyan_frame"></div>-->
  <div id="SOHUCS"></div>
  <script charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/changyan.js"></script>
  <script type="text/javascript">
    window.changyan.api.config({
      appid: 'xxxx',
      conf: 'xxxxxxxxx'
    });
  </script>
</section>
    



    <div class="scroll" id="post-nav-button">
        
            <a  href="/" title="回到主页"><i class="fa fa-home"></i></a>
        
        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>
        
            <a  href="/2017/09/27/browser-rendering/" title="下一篇: 深入浏览器渲染原理(一) — 浏览器渲染DOM过程">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>
    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="/2017/12/25/handlebars/">关于Handlebars.js模板引擎，你想知道的都在这里</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/09/27/browser-rendering/">深入浏览器渲染原理(一) — 浏览器渲染DOM过程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/09/27/vue-state-management/">vue 状态管理的一点思考</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/17/CSS prin/">CSS print 样式</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/16/hexo/">Hexo</a></li></ul>
    <script src="//7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
    <script>
        $(".post-list").addClass("toc-article");
        // $(".post-list-item a").attr("target","_blank");
        $("#post-nav-button > a:nth-child(2)").click(function() {
            $(".fa-bars, .fa-times").toggle();
            $(".post-list").toggle(300);
            if ($(".toc").length > 0) {
                $("#toc, #tocButton").toggle(200, function() {
                    if ($(".switch-area").is(":visible")) {
                        $("#toc, .switch-btn, .switch-area").toggle();
                        $("#tocButton").attr("value", valueHide);
                        }
                    })
            }
            else {
                $(".switch-btn, .switch-area").fadeToggle(300);
            }
        })
    </script>




    <script>
        
    </script>

</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                &copy; 2017 魏阁
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank">Hexo &nbsp;&nbsp;</a><a href="https://github.com/gezi666" target="_blank">Blog</a> by weige
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" >极客到访数: 
                            <span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>, </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit">本页阅读量: 
                            <span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>

    </div>
    <script src="https://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>

    <script>
        $(document).ready(function() {
            var backgroundnum = 1;
            var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
            $("#mobile-nav").css({"background-image": backgroundimg,"background-size": "cover","background-position": "center"});
            $(".left-col").css({"background-image": backgroundimg,"background-size": "cover","background-position": "center"});
        })
    </script>


<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'xxxxx', 'auto');
ga('send', 'pageview');

</script>
<!-- End Google Analytics -->



	<script>
	var _hmt = _hmt || [];
	(function() {
	  var hm = document.createElement("script");
	  hm.src = "//hm.baidu.com/hm.js?xxxxxx";
	  var s = document.getElementsByTagName("script")[0]; 
	  s.parentNode.insertBefore(hm, s);
	})();
	</script>



<div class="scroll" id="scroll">
    <a href="#"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments"><i class="fa fa-comments-o"></i></a>
    <a href="#footer"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    $(document).ready(function() {
        if ($("#comments").length < 1) {
            $("#scroll > a:nth-child(2)").hide();
        };
    })
</script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

  <script language="javascript">
    $(function() {
        $("a[title]").each(function() {
            var a = $(this);
            var title = a.attr('title');
            if (title == undefined || title == "") return;
            a.data('title', title).removeAttr('title').hover(
            function() {
                var offset = a.offset();
                $("<div id=\"anchortitlecontainer\"></div>").appendTo($("body")).html(title).css({
                    top: offset.top - a.outerHeight() - 15,
                    left: offset.left + a.outerWidth()/2 + 1
                }).fadeIn(function() {
                    var pop = $(this);
                    setTimeout(function() {
                        pop.remove();
                    }, pop.text().length * 800);
                });
            }, function() {
                $("#anchortitlecontainer").remove();
            });
        });
    });
</script>


  </div>
</body>
</html>